﻿using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using Pay.Token.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Autofac;

namespace Pay.Token.Controllers {

    /// <summary>
    /// 订单
    /// </summary>
    [RoutePrefix("order_manage")]
    public class OrderManageController : BaseController {
        private IOrderService _iOrderService;
        private ISettingService _iSettingService;
        private IComponentContext _iComponentContext;
        private ILogisticsDetailsService _LogisticsDetailsService;
        private IShopInfoService _iShopInfoService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iOrderService"></param>
        /// <param name="iSettingService"></param>
        /// <param name="iComponentContext"></param>
        public OrderManageController(IOrderService iOrderService, ISettingService iSettingService,
                                     IComponentContext iComponentContext, ILogisticsDetailsService LogisticsDetailsService, IShopInfoService iShopInfoService) {
            _iOrderService = iOrderService;
            _iSettingService = iSettingService;
            _iComponentContext = iComponentContext;
            _LogisticsDetailsService = LogisticsDetailsService;
            _iShopInfoService = iShopInfoService;
        }

        /// <summary>
        /// 立即支付
        /// </summary>
        /// <returns></returns>
        [Route("to_pay"), HttpPost]
        public async Task<ResultMessage<object>> Pay([FromBody]JObject order_no) {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("app待支付订单，立即支付，订单号：" + order_no);
            var jorder_no = GetJsonValue<string>("order_no", order_no);
            var pay_model = new token_check_out_model() { orders = new List<token_order_model>() { new token_order_model() { order_no = jorder_no } } };

            string ip = GetHostAddress();
            log.Info("ip address:" + ip);

            pay_model.ip = ip;
            var model = _iOrderService.GetTokenMallPayOrder(pay_model);
            //DistributionFade.CalcMallProfits(_iComponentContext, model);
            var result = await HChannelApi.Current.PostApi<mall_h5_result>(model);
            if (result == null) {
                throw new ServerErrorException("网络异常");
            }

            if (result.result_code == 1000) {
                return ResultToJson.Json<object>(new { pay_url = result.code_url });
            } else {
                throw new ServerErrorException(result.result_msg);
            }
        }



        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress() {
            string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress)) {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            }
            if (string.IsNullOrEmpty(userHostAddress)) {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip) {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 商户购买的订单
        /// </summary>
        /// <param name="model">查询对象</param>
        /// <returns></returns>
        [Route("list"), HttpGet]
        public ResultMessage<PagedResult<order_dto>> GetBuyOrder([FromUri]OrderQuery model) {
            if (model == null) model = new OrderQuery();
            model.user_id = UserId;
            var result = _iOrderService.Get(model);
            return ResultToJson.Json(result);
        }


        /// <summary>
        /// 买家取消订单
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        [Route("cancel"), HttpGet]
        public ResultMessage<int> Cancel(long order_id) {
            int result = _iOrderService.CloseOrder(order_id);
            if (result > 0)
                return ResultToJson.Json("取消成功", result);
            return ResultToJson.Json<int>("取消失败");
        }

        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="order_id">订单id</param>
        /// <returns></returns>
        [Route("detail"), HttpGet]
        public ResultMessage<order_dto> GetByOrderNo(long order_id) {
            var result = _iOrderService.Get(order_id);
            var shop = _iShopInfoService.GetShopById(result.merchant_id);
            if (shop == null)
                result.mobile = _iSettingService.GetTokenSetting().app.service_phone;
            else
                result.mobile = shop.customer_tel;
            return ResultToJson.Json(result);
        }
        /// <summary>
        ///获取物流信息
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        [Route("order_logistcs"), HttpGet]
        public ResultMessage<order_logistic_results> GetOrderLogistcs(long order_id) {
            var model = _iOrderService.Get(order_id);
            var data = _LogisticsDetailsService.GetList(model);
            var result = new order_logistic_results();
            result.order_id = model.id;
            result.ship_order_number = model.shipping.ship_order_number;
            result.express_company_name = model.shipping.express_company_name;
            result.logistic_results = data;
            return ResultToJson.Json(result);
        }
        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        [Route("confirm"), HttpGet]
        public ResultMessage<int>Confirm(long order_id) {
            var result = _iOrderService.ConfirmOrder(order_id);
            if (result > 0)
                return ResultToJson.Json("收货成功", result);
            return ResultToJson.Json<int>("收货失败");
        }

        /// <summary>
        /// 买家删除订单
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        [Route("delete"), HttpGet]
        public ResultMessage<int> Delete(long order_id) {
            var result = _iOrderService.DeleteOrder(order_id);
            if (result > 0)
                return ResultToJson.Json("删除成功", result);
            return ResultToJson.Json<int>("删除失败");
        }
    }
}
